<template>
    <view class="count-down" v-html="countDown(endDate)">
    </view>
</template>

<script>
import moment from 'moment'
export default {
    props: ['endDate'],
    data() {
        return {
            now: moment()
        }
    },
    mounted() {
        setInterval(()=>{
            this.now = moment()
        },1000)
    },
    destroyed() {
        
    },
    computed: {
        countDown(){
            return function(endDate) {
                let m1 = this.now
                let m2 = moment(endDate)
                let du = moment.duration(m2 - m1, 'ms')
                let hours = du.get('hours')
                let mins = du.get('minutes')
                let ss = du.get('seconds')
                if(hours <= 0 && mins <= 0 && ss <= 0) {
                    this.$emit('timeout')
                    return "今日已结束"
                }else {
                    return `${this.PrefixInteger(hours,2)} <span style="font-size: 16px;">小时</span> ${this.PrefixInteger(mins,2)} <span style="font-size: 16px;">分钟</span><span style="color: #F56C6C;"> ${this.PrefixInteger(ss,2)} </span><span style="font-size: 16px;">秒</span>`
                }
            }
        }
    },
    methods: {
        //数字前补 0 
        // num传入的数字，n需要的字符长度
        PrefixInteger(num, n) {
            return (Array(n).join(0) + num).slice(-n)
        }
    },
}
</script>

<style lang="scss" scoped>
.count-down{
    font-family: "Helvetica Neue";
    text-align: center;
    font-size: 26px;
}
</style>